import {
  config
} from './config.js'
import {
  Format
} from './utils/common'
let station = null
const format = new Format()
App({
  userInfo: null,
  globalData: {
    user: '',
    userInfo: null
  },
  onLaunch(options) {
    console.log("onLaunch" + JSON.stringify(options))
    this.globalData.from = options.path
    // 支付宝更新
    this.autoUpdate()
  },                                                                  
  onShow(options) {
    console.log("ApponShow" + JSON.stringify(options))
    if (options.query && options.query.entityNum) {
      this.globalData.entityNum = options.query.entityNum
      this.globalData.userid = options.query.userid
    } else {
      this.globalData.userid = ''
      this.globalData.entityNum = ''
    }
    if (options.path == 'pages/confirm/confirm' ) {
      if (options.query) {
        let a = options.query
        if (a  && a.myjy_source) {
          this.globalData.station = a
        }
        return
      }
    }
    if (options.path == 'pages/confirm/confirm' || options.path == 'pages/ticket/list/list' || options.path == 'pages/recharge/recharge') {
      if (options.referrerInfo) {
        station = options.referrerInfo.extraData
        this.globalData.modalOpened = false
        this.globalData.station = station
        console.log('456' + station)
      }
    }
    
  },
  autoUpdate() {
    let vm = this
    const updateManager = my.getUpdateManager()
    if (my.canIUse("getUpdateManager")) {
      updateManager.onCheckForUpdate(function (res) {
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function () {
            my.confirm({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  updateManager.applyUpdate()
                } else if (res.cancel) {
                  my.confirm({
                    title: '温馨提示',
                    content: '本次版本更新涉及到新的功能添加，旧版本无法正常访问的哦~',
                    success: function (res) {
                      //第二次提示后，强制更新                      
                      if (res.confirm) {
                        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                        updateManager.applyUpdate()
                      } else {
                        vm.autoUpdate()
                      }
                    }
                  })
                }
              }
            })
          })
          updateManager.onUpdateFailed(function () {
            // 新版本下载失败
            my.alert({
              content: '新版本失败，请退出重试',
              buttonText: '我知道了',
              success: () => {
              }
            });
          })
        } else {
          // console.log('false')
        }
      })
    } else {
      my.confirm({
          title: '提示',
          content: '当前支付宝版本过低，无法使用版本检测功能，请升级到最新版本后重试',
          success: function (res) {
          }
        })
    }
  },
  // 获取支付宝基础信息
  getUserInfo() {
    return new Promise((resolve, reject) => {
      if (this.userInfo) resolve(this.userInfo);
      console.log(this.userInfo)
      my.getAuthCode({
        scopes: ['auth_user'],
        success: authcode => {
          my.getAuthUserInfo({
            success: res => {
              console.log(res)
              this.globalData.data = res
              this.userInfo = res;
              resolve(this.userInfo);
            },
            fail: () => {
              reject({});
            },
          });
        },
        fail: () => {
          reject({});
        },
      });
    });
  },
  // 登录
  myLogin() {
    let that = this
    if (!that.globalData.station || !that.globalData.station.alipay_store_id) {
      // 总shopid
      var store_id = config.shopId // test 2019112600077000000084989653
      this.globalData.mainStore = config.shopId // test 2019112600077000000084989653
    } else {
      var store_id = that.globalData.station.alipay_store_id
    }
    return new Promise((resolve, reject) => {
      my.getAuthCode({
        scopes: ['auth_base'], //auth_base 静默授权； auth_user 弹框授权
        success: authcode => {
          my.showLoading({
            content: '加载中',
          })
          if (my.canIUse('request')) {
            my.request({
              url: config.api_bais + 'ant/auth2',
              data: {
                code: authcode.authCode,
                shopid: store_id
              },
              method: 'POST',
              headers: {
                'content-type': 'application/json'
              },
              success: res => {
                let r = res.data.data
                if(res.data.result== 500) {
                  my.showToast({
                    type: 'none',
                    content: '获取信息失败，请重试',
                    duration: 1000,
                  });
                  reject({});
                } else {
                  my.setStorageSync({
                    key: 'userId',
                    data: r
                  });
                  this.globalData.user = r
                  this.globalData.sessionId = r.sessionId
                  resolve(r)
                }
              },
              fail: (error) => {
                my.hideLoading();
                console.log('fail')
                reject({});
              },

            })
          } else {
            console.log('httpRequest')
            my.request({
              url: config.api_bais + 'ant/auth2',
              data: {
                code: authcode.authCode
              },
              headers: {
                'content-type': 'application/json'
                // 'content-type': 'application/x-www-form-urlencoded'
              },
              method: 'POST',
              success: res => {
                let r = res.data.data
                my.setStorageSync({
                  key: 'userId',
                  data: r
                });
                this.globalData.user = r
                this.globalData.sessionId = r.sessionId
                resolve(r)
              },
              fail: (error) => {
                my.hideLoading();
                console.log('fail')
                reject({});
              },

            })
          }
        }
      })
    })
  },
  myoilLogin(authcode,entityNum) {
    let that = this
    if (!that.globalData.station || !that.globalData.station.alipay_store_id) {
      // 总shopid
      var store_id = config.shopId
      this.globalData.mainStore = config.shopId
    } else {
      var store_id = that.globalData.station.alipay_store_id
    }
    return new Promise((resolve, reject) => {
          if (my.canIUse('request')) {
            my.request({
              url: config.api_bais + 'd/program/antProgramApiService/saveAliPhone',
              data: {
                openId: this.globalData.user.openId,
                aliEncryptData: authcode,
                shopId: store_id,
                entityNum: entityNum,
              },
              method: 'POST',
              headers: {
                'content-type': 'application/json'
              },
              success: res => {
                console.log(res.data + 's')
                let r = res.data
                if (res.data) {
                  if (r.result == 500) {
                    my.showToast({
                      type: 'none',
                      content: r.message,
                      duration: 1000,
                    });
                    reject({});
                  } else {
                    // my.setStorageSync({
                    //   key: 'phoneNum',
                    //   data: r.data.phoneNum
                    // });
                    this.globalData.user.phone = r.data.phoneNum
                    this.globalData.user.cardAsn = r.data.cardAsn
                    resolve(r)
                  }
                } else {
                  my.showToast({
                      type: 'none',
                      content: '错误',
                      duration: 1000,
                    });
                  reject({});
                }

              },
              fail: (error) => {
                console.log('fail')
                reject({});
              },

            })
          } else {
            console.log('httpRequest')
            my.request({
              url: config.api_bais + 'd/program/antProgramApiService/saveAliPhone',
              data: {
                openId: this.globalData.user.openId,
                aliEncryptData: authcode,
                shopId: station.alipay_store_id
              },
              method: 'POST',
              headers: {
                'content-type': 'application/json'
              },
              success: res => {
                let r = res.data
                my.setStorageSync({
                  key: 'phoneNum',
                  data: r.data.phoneNum
                });
                this.globalData.user.phoneNum = r.data.phoneNum
                this.globalData.user.cardAsn = r.data.cardAsn
                resolve(r)

              },
              fail: (error) => {
                console.log('fail')
                reject({});
              },

            })

          }
        // }
      // })
    })
  },
  getLocation() {
    var that = this;
    return new Promise((resolve, reject) => {
      my.getLocation({ type: 3,
        success(res) {
          // console.log(res)
          let userLocation = {
            userX: res.longitude,
            userY: res.latitude,
          }
          if (res.district && res.pois && res.pois[0]) {
            userLocation.address = res.district + res.pois[0].name
          } else {
            userLocation.address = '获取当前位置失败'
          }
          that.globalData.userLocation = userLocation
          my.request({
            url: config.api_bais + 'd/program/antProgramApiService/getNearestStation',
            data: {
              x: res.longitude,
              y: res.latitude
            },
            method: 'POST',
            headers: {
              'content-type': 'application/json'
            },
            success: res => {
              let r = res.data.data
              if(res.data.result== 500) {
                my.showToast({
                  type: 'none',
                  content: '获取油站信息失败，请重试',
                  duration: 1000,
                });
                reject({});
              }
              if (res.data.result== 200) {
                if (res.data.data == '未找到附近加油站') {
                  let err= {
                    code: 2,
                    msg: '您当前不在服务区，请前往壳牌加油站进行加油'
                  }
                  my.hideLoading();
                  reject(err);
                  return
                }
                station = {
                  alipay_store_id: res.data.data.shopId,
                  // alipay_store_id:'2019111900077000000084753577',  // test1 2019112600077000000084989653
                  store_id: '',
                  oil_num: '92#',
                  myjy_source: 'mayijiayou',

                  stationX: res.data.data.posX,
                  stationY: res.data.data.posY,
                  innerOrgCode: res.data.data.innerOrgCode,
                  name: res.data.data.name,
                  address: res.data.data.address,
                }
                that.globalData.station = station
                resolve(station);
              }
            },
            fail: (error) => {
              let err= {
                code: 1,
                msg: '获取油站失败，请退出重试'
              }
              my.hideLoading();
              reject(err);
            },
            complete: (e) => {
              // console.log('定位complete' + JSON.stringify(e))
              // console.log(e)
            }
          })
        },
        fail: (error) => {
          console.log(error)
          if (error.error && error.error == 2001) {
            let err= {
              code: 0,
            }
            my.hideLoading();
            reject(err);
          } else {
            my.alert({content:error.errorMessage})
            reject();
          }
          
        },
      })
    })
  },
  toMayi() {
    my.navigateToMiniProgram({
      appId: '2019110168820582', //生产
      extraData: {
        // "data1": "test"
      },
      success: (res) => {
        console.log(JSON.stringify(res))
      },
      fail: (res) => {
        console.log(JSON.stringify(res))
      }
    });
  },
  backMayi() {
    my.navigateBackMiniProgram({
      extraData: {
        // "data1": "test"
      },
      success: (res) => {
        console.log(JSON.stringify(res))
      },
      fail: (res) => {
        console.log(JSON.stringify(res))
      }
    });
  }
});